﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;

namespace CS.Serialization
{
    /// <summary>
    /// Xml序列化
    /// </summary>
    public class Serializer
    {

        ///// <summary>
        ///// 对像序列化成JSON格式
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="obj"></param>
        ///// <returns></returns>
        //public static string JsonSerialize<T>(T obj)
        //{
        //    return JsonConvert.SerializeObject(obj);
        //}

        ///// <summary>
        ///// Json格式字符串反序列化成对象
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="jsonString"></param>
        ///// <returns></returns>
        //public static T JsonXDeserialize<T>(string jsonString)
        //{
        //    return JsonConvert.DeserializeObject<T>(jsonString);
        //}


        /// <summary>
        /// 对象序列化成 XML String
        /// </summary>
        public static string XmlSerialize<T>(T obj)
        {
            string xmlString;
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (var ms = new MemoryStream())
            {
                xmlSerializer.Serialize(ms, obj);
                xmlString = Encoding.UTF8.GetString(ms.ToArray());
            }
            return xmlString;
        }

        /// <summary>
        /// XML String 反序列化成对象
        /// </summary>
        public static T XmlDeserialize<T>(string xmlString)
        {
            T t;
            var xmlSerializer = new XmlSerializer(typeof(T));
            using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString)))
            using (XmlReader xmlReader = XmlReader.Create(xmlStream))
            {
                var obj = xmlSerializer.Deserialize(xmlReader);
                t = (T)obj;
            }
            return t;
        }
    }
}
